#!/usr/bin/env node

// 控制台添加单词工具
const fs = require('fs');
const readline = require('readline');

// 词库文件路径
const LEXICON_FILES = {
  'cet4': './cet4-words-100.json',
  'cet6': './cet6-words-100.json',
  'toefl': './toefl-words-100.json'
};

// 创建readline接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 询问用户输入的函数
function askQuestion(question) {
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      resolve(answer.trim());
    });
  });
}

// 加载词库数据
function loadLexicon(set) {
  try {
    const data = fs.readFileSync(LEXICON_FILES[set], 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.error(`加载词库 ${set} 失败:`, error.message);
    return [];
  }
}

// 保存词库数据
function saveLexicon(set, data) {
  try {
    fs.writeFileSync(LEXICON_FILES[set], JSON.stringify(data, null, 2));
    console.log(`✅ 词库 ${set} 保存成功！`);
    return true;
  } catch (error) {
    console.error(`保存词库 ${set} 失败:`, error.message);
    return false;
  }
}

// 获取下一个ID
function getNextId(words) {
  return words.reduce((max, word) => Math.max(max, word.id || 0), 0) + 1;
}

// 验证输入
function validateInput(word, meaning) {
  if (!word || word.length === 0) {
    return '单词不能为空';
  }
  if (!meaning || meaning.length === 0) {
    return '释义不能为空';
  }
  return null;
}

// 添加单词到词库
async function addWordToLexicon(set, wordData) {
  const words = loadLexicon(set);
  
  // 检查单词是否已存在
  const exists = words.find(w => w.word.toLowerCase() === wordData.word.toLowerCase());
  if (exists) {
    console.log(`❌ 单词 "${wordData.word}" 已存在于 ${set} 词库中！`);
    return false;
  }
  
  // 添加新单词
  const newWord = {
    id: getNextId(words),
    ...wordData,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  };
  
  words.push(newWord);
  
  // 保存到文件
  if (saveLexicon(set, words)) {
    console.log(`✅ 成功添加单词 "${wordData.word}" 到 ${set} 词库！`);
    console.log(`📊 ${set} 词库现在有 ${words.length} 个单词`);
    return true;
  }
  
  return false;
}

// 显示词库统计
function showLexiconStats() {
  console.log('\n📚 当前词库统计:');
  console.log('='.repeat(40));
  
  Object.keys(LEXICON_FILES).forEach(set => {
    const words = loadLexicon(set);
    console.log(`${set.toUpperCase()}: ${words.length} 个单词`);
  });
  console.log('='.repeat(40));
}

// 主函数
async function main() {
  console.log('🎯 快背单词 - 控制台添加单词工具');
  console.log('='.repeat(50));
  
  // 显示当前统计
  showLexiconStats();
  
  try {
    // 选择词库
    console.log('\n📖 请选择要添加单词的词库:');
    console.log('1. CET4');
    console.log('2. CET6');
    console.log('3. TOEFL');
    console.log('4. 退出');
    
    const choice = await askQuestion('\n请输入选择 (1-4): ');
    
    if (choice === '4') {
      console.log('👋 再见！');
      rl.close();
      return;
    }
    
    const setMap = { '1': 'cet4', '2': 'cet6', '3': 'toefl' };
    const set = setMap[choice];
    
    if (!set) {
      console.log('❌ 无效的选择！');
      rl.close();
      return;
    }
    
    console.log(`\n📝 向 ${set.toUpperCase()} 词库添加新单词:`);
    console.log('-'.repeat(30));
    
    // 获取单词信息
    const word = await askQuestion('单词: ');
    const phonetic = await askQuestion('音标 (可选): ');
    const meaning = await askQuestion('释义: ');
    const partOfSpeech = await askQuestion('词性 (如: n., v., adj., adv.): ');
    const difficulty = await askQuestion('难度 (1-5, 默认3): ');
    const frequency = await askQuestion('频率 (1-5, 默认3): ');
    const example = await askQuestion('例句 (可选): ');
    const exampleMeaning = await askQuestion('例句翻译 (可选): ');
    const synonyms = await askQuestion('同义词 (用逗号分隔, 可选): ');
    const antonyms = await askQuestion('反义词 (用逗号分隔, 可选): ');
    const tags = await askQuestion('标签 (用逗号分隔, 可选): ');
    
    // 验证输入
    const validationError = validateInput(word, meaning);
    if (validationError) {
      console.log(`❌ ${validationError}`);
      rl.close();
      return;
    }
    
    // 构建单词数据
    const wordData = {
      word: word.trim(),
      phonetic: phonetic.trim() || '',
      meaning: meaning.trim(),
      partOfSpeech: partOfSpeech.trim() || '',
      difficulty: parseInt(difficulty) || 3,
      frequency: parseInt(frequency) || 3,
      example: example.trim() || '',
      exampleMeaning: exampleMeaning.trim() || '',
      synonyms: synonyms ? synonyms.split(',').map(s => s.trim()).filter(s => s) : [],
      antonyms: antonyms ? antonyms.split(',').map(s => s.trim()).filter(s => s) : [],
      tags: tags ? tags.split(',').map(s => s.trim()).filter(s => s) : []
    };
    
    // 显示确认信息
    console.log('\n📋 单词信息确认:');
    console.log('-'.repeat(30));
    console.log(`单词: ${wordData.word}`);
    console.log(`音标: ${wordData.phonetic || '(无)'}`);
    console.log(`释义: ${wordData.meaning}`);
    console.log(`词性: ${wordData.partOfSpeech || '(无)'}`);
    console.log(`难度: ${wordData.difficulty}`);
    console.log(`频率: ${wordData.frequency}`);
    console.log(`例句: ${wordData.example || '(无)'}`);
    console.log(`例句翻译: ${wordData.exampleMeaning || '(无)'}`);
    console.log(`同义词: ${wordData.synonyms.length > 0 ? wordData.synonyms.join(', ') : '(无)'}`);
    console.log(`反义词: ${wordData.antonyms.length > 0 ? wordData.antonyms.join(', ') : '(无)'}`);
    console.log(`标签: ${wordData.tags.length > 0 ? wordData.tags.join(', ') : '(无)'}`);
    
    const confirm = await askQuestion('\n确认添加这个单词吗？(y/n): ');
    
    if (confirm.toLowerCase() === 'y' || confirm.toLowerCase() === 'yes') {
      await addWordToLexicon(set, wordData);
    } else {
      console.log('❌ 已取消添加');
    }
    
    // 询问是否继续
    const continueChoice = await askQuestion('\n是否继续添加其他单词？(y/n): ');
    if (continueChoice.toLowerCase() === 'y' || continueChoice.toLowerCase() === 'yes') {
      console.log('\n' + '='.repeat(50));
      await main(); // 递归调用继续添加
    } else {
      console.log('👋 再见！');
    }
    
  } catch (error) {
    console.error('❌ 发生错误:', error.message);
  } finally {
    rl.close();
  }
}

// 启动程序
if (require.main === module) {
  main().catch(console.error);
}

module.exports = { addWordToLexicon, loadLexicon, saveLexicon };
